<template>
  <div class="app-container">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :span="6">
        <div class="card total-lots">
          <div class="card-body">
            <div class="card-left">
              <el-icon :size="52" color="#fff"><Parking /></el-icon>
            </div>
            <div class="card-right">
              <div class="card-title">总停车场</div>
              <div class="card-number">{{ total }}</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card total-spots">
          <div class="card-body">
            <div class="card-left">
              <el-icon :size="52" color="#fff"><LocationOutline /></el-icon>
            </div>
            <div class="card-right">
              <div class="card-title">总泊位数</div>
              <div class="card-number">{{ totalParkingSpots }}</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card used-spots">
          <div class="card-body">
            <div class="card-left">
              <el-icon :size="52" color="#fff"><Car /></el-icon>
            </div>
            <div class="card-right">
              <div class="card-title">已用泊位</div>
              <div class="card-number">{{ usedParkingSpots }}</div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="card free-spots">
          <div class="card-body">
            <div class="card-left">
              <el-icon :size="52" color="#fff"><Time /></el-icon>
            </div>
            <div class="card-right">
              <div class="card-title">空闲泊位</div>
              <div class="card-number">{{ freeParkingSpots }}</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索区域优化 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="停车场名称" prop="lotName">
          <el-input v-model="queryParams.lotName" placeholder="请输入停车场名称" clearable size="small">
            <template #prefix>
              <el-icon class="el-input__icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="停车场类型" prop="lotType">
          <el-select v-model="queryParams.lotType" placeholder="请选择停车场类型" clearable size="small">
            <el-option label="路边停车场" value="1">
              <el-icon><LocationOutline /></el-icon> 路边停车场
            </el-option>
            <el-option label="室内场库" value="2">
              <el-icon><OfficeBuilding /></el-icon> 室内场库
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <el-row :gutter="10" class="mb8 operation-wrapper">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增停车场</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-download" size="small">导出数据</el-button>
      </el-col>
    </el-row>

    <!-- 表格优化 -->
    <el-card class="table-wrapper">
      <el-table v-loading="loading" :data="lotList" stripe border highlight-current-row>
        <el-table-column label="停车场名称" align="center" prop="lotName" min-width="150">
          <template slot-scope="scope">
            <el-link type="primary" :underline="false">{{ scope.row.lotName }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="所属区域" align="center" prop="areaName" :formatter="formatArea" />
        <el-table-column label="所属道路" align="center" prop="roadName" :formatter="formatRoad" />
        <el-table-column label="停车场类型" align="center" prop="lotType" width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.lotType === '1' ? 'warning' : 'success'" effect="dark">
              <i :class="scope.row.lotType === '1' ? 'el-icon-location-outline' : 'el-icon-office-building'"></i>
              {{ scope.row.lotType === '1' ? '路边' : '场库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="泊位统计" align="center">
          <template slot-scope="scope">
            <el-tooltip effect="dark" placement="top">
              <div slot="content">
                总泊位: {{ scope.row.totalSpots }}<br>
                已用: {{ scope.row.usedSpots }}<br>
                空闲: {{ scope.row.freeSpots }}
              </div>
              <el-progress
                :percentage="Number(calculatePercentage(
                  Number(scope.row.usedSpots) || 0,
                  Number(scope.row.totalSpots) || 1
                ))"
                :format="format"
                :colors="customColors">
              </el-progress>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="使用率" align="center" prop="useRate">
          <template slot-scope="scope">
            <el-progress
              :percentage="Number(scope.row.useRate || 0)"
              :format="percentageFormat">
            </el-progress>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0"
                 :total="total"
                 :page.sync="queryParams.pageNum"
                 :limit.sync="queryParams.pageSize"
                 @pagination="getList"
                 class="pagination-wrapper" />
    </el-card>

    <!-- 对话框优化 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body custom-class="custom-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="停车场名称" prop="lotName">
              <el-input v-model="form.lotName" placeholder="请输入停车场名称">
                <i slot="prefix" class="el-input__icon el-icon-parking"></i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="停车场类型" prop="lotType">
              <el-select v-model="form.lotType" placeholder="请选择停车场类型" style="width: 100%">
                <el-option label="路边停车场" value="1">
                  <i class="el-icon-location-outline"></i> 路边停车场
                </el-option>
                <el-option label="室内场库" value="2">
                  <i class="el-icon-office-building"></i> 室内场库
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="总泊位数" prop="totalSpots">
          <el-input-number v-model="form.totalSpots" :min="0" />
        </el-form-item>
        <el-form-item label="已用泊位" prop="usedSpots">
          <el-input-number v-model="form.usedSpots" :min="0" :max="form.totalSpots" />
        </el-form-item>
        <el-form-item label="所属区域" prop="areaId">
          <el-select v-model="form.areaId" placeholder="请选择所属区域" @change="handleAreaChange">
            <el-option
              v-for="area in areaOptions"
              :key="area.areaId"
              :label="area.areaName"
              :value="area.areaId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属道路" prop="roadId">
          <el-select v-model="form.roadId" placeholder="请选择所属道路">
            <el-option
              v-for="road in roadOptions"
              :key="road.roadId"
              :label="road.roadName"
              :value="road.roadId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parkingApi } from '@/api/parking'

export default {
  name: "ParkingLotList",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      lotList: [],
      title: "",
      open: false,
      form: {
        lotId: undefined,
        lotName: undefined,
        lotType: undefined,
        totalSpots: 0,
        usedSpots: 0,
        areaId: undefined,
        roadId: undefined
      },
      rules: {
        lotName: [
          { required: true, message: "停车场名称不能为空", trigger: "blur" }
        ],
        lotType: [
          { required: true, message: "停车场类型不能为空", trigger: "change" }
        ],
        totalSpots: [
          { required: true, message: "总泊位数不能为空", trigger: "blur" }
        ],
        areaId: [
          { required: true, message: "所属区域不能为空", trigger: "change" }
        ],
        roadId: [
          { required: true, message: "所属道路不能为空", trigger: "change" }
        ]
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        lotName: undefined,
        lotType: undefined
      },
      areaOptions: [], // 区域选项
      roadOptions: [], // 道路选项
      areaMap: new Map(), // 用于缓存区域信息
      roadMap: new Map(), // 用于缓存道路信息
      totalParkingSpots: 0,
      usedParkingSpots: 0,
      freeParkingSpots: 0,
      customColors: [
        {color: '#67C23A', percentage: 60},
        {color: '#E6A23C', percentage: 80},
        {color: '#F56C6C', percentage: 100}
      ]
    };
  },
  created() {
    this.getList();
    this.getAreaListAll();
  },
  methods: {
    getList() {
      this.loading = true;
      parkingApi.getParkingLotList(this.queryParams).then(response => {
        this.lotList = response.data.rows;
        this.total = response.data.total;

        // 计算统计数据
        this.totalParkingSpots = this.lotList.reduce((sum, lot) => sum + lot.totalSpots, 0);
        this.usedParkingSpots = this.lotList.reduce((sum, lot) => sum + lot.usedSpots, 0);
        this.freeParkingSpots = this.totalParkingSpots - this.usedParkingSpots;

        // 确保使用率是有效数字
        this.lotList = this.lotList.map(item => ({
          ...item,
          useRate: item.useRate ? parseFloat(item.useRate) : 0
        }));

        this.loading = false;
      }).catch(error => {
        this.loading = false;
        this.$message.error('获取数据失败，请刷新重试');
        console.error('Error:', error);
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.getAreaListAll();
      this.open = true;
      this.title = "添加停车场";
    },
    handleUpdate(row) {
      this.reset();
      this.getAreaListAll();
      parkingApi.getParkingLotInfo(row.lotId).then(response => {
        this.form = response.data;
        if (this.form.areaId) {
          this.getRoadListByArea(this.form.areaId);
        }
        this.open = true;
        this.title = "修改停车场";
      });
    },
    handleDelete(row) {
      const lotName = row.lotName;
      this.$confirm('是否确认删除"' + lotName + '"停车场？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return parkingApi.deleteParkingLot(row.lotId);
      }).then(response => {
        if (response.code === 200) {
          this.$message.success("删除成功");
          this.getList();
        } else {
          this.$message.error(response.msg);
        }
      }).catch(() => {});
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '处理中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          if (this.form.lotId) {
            // 修改
            parkingApi.updateParkingLot(this.form).then(response => {
              loading.close();
              if (response.code === 200) {
                this.$message.success("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.$message.error(response.msg || '修改失败');
              }
            }).catch(error => {
              loading.close();
              this.$message.error('系统错误，请稍后重试');
              console.error('Error:', error);
            });
          } else {
            // 新增
            parkingApi.addParkingLot(this.form).then(response => {
              loading.close();
              if (response.code === 200) {
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.$message.error(response.msg || '新增失败');
              }
            }).catch(error => {
              loading.close();
              this.$message.error('系统错误，请稍后重试');
              console.error('Error:', error);
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        lotId: undefined,
        lotName: undefined,
        lotType: undefined,
        totalSpots: 0,
        usedSpots: 0,
        areaId: undefined,
        roadId: undefined
      };
      this.roadOptions = [];
      if (this.$refs["form"]) {
        this.$refs["form"].resetFields();
      }
    },
    formatArea(row) {
      if (!row.areaId) return '';
      if (this.areaMap.has(row.areaId)) {
        return this.areaMap.get(row.areaId);
      }
      parkingApi.getAreaInfo(row.areaId).then(response => {
        if (response.code === 200 && response.data) {
          const areaName = response.data.areaName;
          this.areaMap.set(row.areaId, areaName);
          this.$forceUpdate();
          return areaName;
        }
      });
      return '加载中...';
    },
    formatRoad(row) {
      if (!row.roadId) return '';
      if (this.roadMap.has(row.roadId)) {
        return this.roadMap.get(row.roadId);
      }
      parkingApi.getRoadInfo(row.roadId).then(response => {
        if (response.code === 200 && response.data) {
          const roadName = response.data.roadName;
          this.roadMap.set(row.roadId, roadName);
          this.$forceUpdate();
          return roadName;
        }
      });
      return '加载中...';
    },
    getAreaListAll() {
      parkingApi.getAreaList().then(response => {
        if (response.code === 200) {
          this.areaOptions = response.data;
          this.areaOptions.forEach(area => {
            this.areaMap.set(area.areaId, area.areaName);
          });
        }
      }).catch(() => {
        this.$message.error('获取区域列表失败');
      });
    },
    getRoadListByArea(areaId) {
      if (!areaId) {
        this.roadOptions = [];
        return;
      }
      parkingApi.getRoadListByArea(areaId).then(response => {
        if (response.code === 200) {
          this.roadOptions = response.data;
          this.roadOptions.forEach(road => {
            this.roadMap.set(road.roadId, road.roadName);
          });
        }
      }).catch(() => {
        this.$message.error('获取道路列表失败');
      });
    },
    handleAreaChange(areaId) {
      this.form.roadId = undefined;
      if (areaId) {
        this.getRoadListByArea(areaId);
      }
    },
    calculatePercentage(used, total) {
      if (!total || total === 0) return 0;
      const percentage = Math.floor((used / total) * 100);
      return Math.min(Math.max(percentage, 0), 100);
    },
    format(percentage) {
      const value = Number(percentage) || 0;
      return `${Math.min(Math.max(Math.round(value), 0), 100)}%`;
    },
    percentageFormat(percentage) {
      const value = Number(percentage) || 0;
      return `${Math.min(Math.max(Math.round(value * 10) / 10, 0), 100)}%`;
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  background: #f0f2f5;
  padding: 20px;
  min-height: calc(100vh - 84px);

  .panel-group {
    margin-bottom: 24px;

    .card {
      height: 120px;
      padding: 24px;
      border-radius: 12px;
      box-shadow: 0 4px 20px 0 rgba(0,0,0,.1);
      transition: all .3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0,0,0,.2);
      }

      .card-body {
        display: flex;
        align-items: center;
        height: 100%;

        .card-left {
          flex: 0 0 70px;
          font-size: 52px;
          color: #fff;
          text-align: center;
          text-shadow: 2px 2px 4px rgba(0,0,0,.2);
        }

        .card-right {
          flex: 1;
          padding-left: 20px;

          .card-title {
            font-size: 16px;
            color: rgba(255,255,255,.9);
            margin-bottom: 8px;
          }

          .card-number {
            font-size: 28px;
            font-weight: bold;
            color: #fff;
          }
        }
      }
    }

    .total-lots {
      background: linear-gradient(45deg, #1890ff 30%, #36cfc9 90%);
    }

    .total-spots {
      background: linear-gradient(45deg, #722ed1 30%, #eb2f96 90%);
    }

    .used-spots {
      background: linear-gradient(45deg, #fa8c16 30%, #faad14 90%);
    }

    .free-spots {
      background: linear-gradient(45deg, #52c41a 30%, #73d13d 90%);
    }
  }

  .search-wrapper {
    margin-bottom: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,.05);
    background: #fff;

    .el-form {
      padding: 24px;
    }
  }

  .operation-wrapper {
    margin-bottom: 24px;

    .el-button {
      padding: 10px 20px;
      border-radius: 6px;

      &:hover {
        transform: translateY(-2px);
        transition: all .3s ease;
      }
    }
  }

  .table-wrapper {
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,.05);
    background: #fff;

    .el-table {
      border-radius: 12px;
      overflow: hidden;

      th {
        background-color: #fafafa;
        color: #606266;
        font-weight: 600;
        padding: 12px 0;
      }

      td {
        padding: 12px 0;
      }
    }

    .el-tag {
      border-radius: 4px;
      padding: 0 12px;
      height: 28px;
      line-height: 26px;
    }

    .el-progress {
      width: 150px;
      margin: 0 auto;
    }
  }

  .pagination-wrapper {
    margin-top: 24px;
    padding: 16px;
    text-align: right;
    background: #fff;
    border-radius: 8px;
  }
}

.custom-dialog {
  .el-dialog {
    border-radius: 12px;
    overflow: hidden;

    .el-dialog__header {
      padding: 24px;
      background: #fafafa;
      border-bottom: 1px solid #f0f0f0;
      margin: 0;

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }

    .el-dialog__body {
      padding: 32px 24px;
    }

    .el-dialog__footer {
      padding: 24px;
      border-top: 1px solid #f0f0f0;

      .el-button {
        padding: 10px 24px;
        border-radius: 6px;
      }
    }
  }
}

:deep(.el-input__inner) {
  border-radius: 6px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-table) {
  .el-button--mini {
    padding: 7px 15px;
  }
}
</style>
